#include "cboundingsphere.h"

CBoundingSphere::CBoundingSphere(void *pObject, CPoint3f Center, double fRadius)
{
    this->m_pBoundedObject = pObject;
    this->m_Position = Center;
    this->m_fRadius = fRadius;
}

CBoundingSphere::~CBoundingSphere()
{

}

bool CBoundingSphere::intersect(CRay* pRay)
{
    CVector3f oToPos(this->m_Position - pRay->m_Start);
    float tca = oToPos*pRay->m_Direction;

    if (tca < 0.0)
        return false;

    float d2 = oToPos.length2() - pow(tca,2.0);
    float r2 = pow(this->m_fRadius, 2.0);

    if (d2 < 0.0 || d2 > r2)
        return false;

    return true;
}

bool CBoundingSphere::intersect(CBoundingSphere *pSphere)
{
    double fDistance2 = this->m_Position.Distance2(pSphere->m_Position);
    double fMinDistance2 = pow(this->m_fRadius,2.0) + pow(pSphere->m_fRadius, 2.0);

    if (fDistance2 > fMinDistance2)
        return false;
    return true;
}

std::string CBoundingSphere::className()
{
    return std::string("CBoundingSphere");
}

void CBoundingSphere::getBoundingBox(CPoint3f &Pmin, CPoint3f &Pmax)
{
    Pmin.Set(this->m_Position.GetX()-this->m_fRadius, this->m_Position.GetY()-this->m_fRadius, this->m_Position.GetZ()-this->m_fRadius);
    Pmax.Set(this->m_Position.GetX()+this->m_fRadius, this->m_Position.GetY()+this->m_fRadius, this->m_Position.GetZ()+this->m_fRadius);
}
